package com.company.test19;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.*;

/**
 * Created by Administrator on 2016.9.24.
 */
public class BigOutputStream {
    private File file;
    private String vessel;
    private DataOutputStream output;

    BigOutputStream(File file) throws IOException{
        this.file=file;
        vessel="";
        output =new DataOutputStream(new BufferedOutputStream(new FileOutputStream(this.file,true)));
    }

    public void writeBit(char bit) throws IOException {
        if(vessel.length()<8){
            vessel=vessel+bit;
            return;
        }

        vessel=vessel+bit;
        output();
        vessel="";
    }

    public void writeBit(String bit)throws IOException{
        while (bit.length()+vessel.length()>=8){
            int sign=8-vessel.length();
            vessel=vessel+bit.substring(0,sign);
            bit=bit.substring(sign);
            output();
            vessel="";
        }

        vessel=vessel+bit;
    }

    private void output() throws IOException {
        byte bit=0;
        try{
            int number=0;
            for(int i=0;i<vessel.length();i++){
                number=number*2+vessel.charAt(i)-'0';
            }
            bit=Byte.valueOf(number+"");
        }catch (Exception e){
            System.out.println("你的输入有误，输入的参数不该含有0与1以外的字符");
            System.out.println(e.toString());
            return;
        }
        output.write(bit);
        return;
    }

    public void close()throws IOException{
        for(int i=0;i<8-vessel.length();i++){
            vessel=vessel+"0";
        }

        output();
        output.close();
    }

    public static void main(String[] args)throws IOException{
        BigOutputStream output=new BigOutputStream(
                new File("src/com/company/test19/Exercise1917.dat"));

        String str="010000100100001001101";
        output.writeBit(str);
        output.close();
    }
}